package com.gec.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class JDBCUtils {

	static Properties p = new Properties();

	//静态的连接
	static Connection conn;
	static PreparedStatement ps ;
	static ResultSet rs ;

	public static Connection getConn() {
		return conn;
	}

	public static PreparedStatement getPs() {
		return ps;
	}

	public static ResultSet getRs() {
		return rs;
	}

	static{
		try(InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties")){
			//把流加载到properties ，就会给properties键值对
			p.load(is);

			//加载驱动

			try {
				Class.forName(p.getProperty("driver"));
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}

		}catch (IOException e){
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		System.out.println(p.getProperty("username"));
	}

	//获取连接的方法
	public static Connection getConnection(){
		try {
			conn = DriverManager.getConnection(p.getProperty("url"),p.getProperty("username"),p.getProperty("password"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/*
       已知：sql,参数的数组
       这里要完成  给问号设置值，执行查询，返回结果集
     */
	public static ResultSet executeQuery(String sql, Object... params) {
		try{
			//获取连接
			conn = getConnection();
			//预编译语句对象
			ps = conn.prepareStatement(sql);
			//参数不确定，要判断
			if(params.length > 0){
				for (int i = 0;i<params.length;i++) {
					//给问号设置值
					ps.setObject(i+1,params[i]);
				}
			}
			//打印执行语句
			System.out.println("执行的sql：" + ps);
			//执行查询
			rs = ps.executeQuery();

			//返回结果集
			return rs;
		}catch (SQLException e){
			e.printStackTrace();
		}
		return null;
	}

	public static void close(Connection conn, PreparedStatement pstm, ResultSet rs) {
		try{
			if(rs != null){
				rs.close();
			}

			if(pstm != null){
				pstm.close();
			}

			if(conn != null){
				conn.close();
			}
		}catch (SQLException e){
			e.printStackTrace();
		}
	}

	/*
    统一封装dml操作
     */
	public static void executeUpdate(String sql, Object... params) {
		conn = getConnection();
		try {
			ps = conn.prepareStatement(sql);
			//判定
			if(params != null && params.length>0){
				for(int i = 0;i<params.length;i++){
					//给问号赋值
					ps.setObject(i+1,params[i]);
				}
			}
			//打印执行语句
			System.out.println("执行的sql：" + ps);
			//执行
			ps.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
